﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using ESecretary.WinUI;
using ESecretary.MyCommon;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;

namespace ESecretary
{
    static class Program
    {
        private const int WS_SHOWNORMAL = 1;

        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);


        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        private static void Main()
        {
            Process instance = RunningInstance();
            if (instance == null)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                new FrmLogin().ShowDialog();
                if (GlobalVar.LoginName != null)
                {
                    Application.Run(new FrmMain());
                }
            }
            else
            {
                HandleRunningInstance(instance);
                MessageBox.Show("已经启动了一个程序！");
            }
        }
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if ((process.Id != current.Id) && (Assembly.GetExecutingAssembly().Location.Replace("/", @"\") == current.MainModule.FileName))
                {
                    return process;
                }
            }
            return null;
        }


        public static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, 1);
            SetForegroundWindow(instance.MainWindowHandle);
        }       
    }

    public class Test
    {
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //Application.Run(new ESecretary.WinUI.Form1());
            
        }
    }
}